<?php
namespace App\Middlewares;

use App\Facades\Db;
use App\Logics\MenuLogic;
use App\Models\Base\Content;
use Core\Context;
use Core\Session;

class AdminPermission{

    /**
     * 中间件的处理逻辑，接收request, 返回response对象
     *
     * @param $request 原始对象，不做处理
     * @param  \Closure  $next
     * @return mixed
     * @author lichunguang 153102250@qq.com
     * @since 2022/8/22 上午10:05
     */
    public function handle($request, \Closure $next){
        //return $next($request);
        $prefix = '/'.config('admin_dir');
        $uri = get_current_route();

        $publicUrls = [
            $prefix.'/main/welcome', //后台框架欢迎页
            $prefix.'/main/index', //后台框架首页
            $prefix.'/main/noPermission', //暂无权限的页面
            $prefix.'/main/userinfo', //管理员信息
            $prefix.'/main/saveUserInfo', //修改自己的用户信息
            $prefix.'/main/changePassword', //修改自己的密码
            $prefix.'/uploads/upload', //上传文件
            $prefix.'/main/logout' //退出登录
        ];
        if(in_array($uri, $publicUrls)){
            return $next($request);
        }
        $adminRoleId = Context::get('adminRoleId');
        //$noPermissionUrl = $prefix . '/main/noPermission';
        $noPermissionUrl = url('main/noPermission');
        //校验jwt token的有效性，先跳过
        try{
            $uriList = (new MenuLogic())->getPermissionUrlByRoleId($adminRoleId);
            //print_r($uriList);exit;
            Context::set('adminPermission', $uriList);
            //print_r(Context::get('adminPermission'));exit;
            if(empty($uriList)){
                redirect($noPermissionUrl);
            }
            $uri = get_current_route();
            $pos = strpos($uri,'/', 1);
            //原始链接
            $uriOrigin = '/admin'. substr($uri, $pos);
            return $next($request);
            if(in_array($uriOrigin, $uriList)){
                return $next($request);
            }else{
                if($request->ajax()){
                    return api_error('没有权限', 500);
                }else{
                    redirect($noPermissionUrl);
                }
            }

        }catch (\Exception $e) {
            if ($request->ajax()) {
                return api_error($e->getMessage(), 500);
            } else {
                redirect($noPermissionUrl);
            }
        }
    }

}